<?php
if (!class_exists('BaseAction')) {
	/**
	 * Main controller action. All other actions must extend this action
	 * @author Alecsandru Gabriel DINU
	 * @since Jun 13, 2008
	 * @Bean(id = "baseAction")  
	 */
	class BaseAction {
		private $context;
		protected $config;
		protected $log;
		
		private $error_messages = array();
		private $success_messages = array();
		private $info_messages = array();
		private $warn_messages = array();
		
		/**
		 * Constructor
		 *
		 * @param Context $context
		 */
		function __construct() {
			$this->log = Logger::getInstance()->getLogger();
			$this->config = AlfaConfiguration::getInstance();
			
			// define some common results
			if (!defined("SUCCESS")) define("SUCCESS", "success");
			if (!defined("ERROR")) define("ERROR", "error");
			if (!defined("INPUT")) define("INPUT", "input");
				
			global $has_errors;
			$has_errors = false;
				
		}

		/**
		 * Setter method for Context object
		 * @param Context
		 */
		public function setContext($context) {
			$this->context = $context;
		}
		
		/**
		 * Gets the context
		 * @return Context
		 */
		public function getContext() {
			return $this->context;
		}
		
		
		/**
		 * Default action. If no action is defined
		 * in the configuration, this method will
		 * be called by default.
		 *
		 * @return unknown
		 */
		public function execute() {
			return "success";
		}
		
		

		public function addSuccessMessage($message) {
			$this->success_messages[] =  $message;
		}
		
		public function addErrorMessage($message) {
			$this->error_messages[] =  $message;
		}
		
		public function addWarningMessage($message) {
			$this->warn_messages[] =  $message;
		}
		
		public function addInfoMessage($message) {
			$this->info_messages[] =  $message;
		}
		
		public function getSuccessMessages() {
			return $this->success_messages;
		}

		public function getErrorMessages() {
			return $this->error_messages;
		}
		
		public function getWarningMessages() {
			return $this->warn_messages;
		}
		
		public function getInfoMessages() {
			return $this->info_messages;
		}
		
		
		public function getText($key = null) {
			return AlfaTranslator::getInstance()->message($key);
		}
		
		public function finalize() {
			// nothing to do			
		}
		 
		protected function toObject($array, $obj) {
			if (!is_object($obj) || !is_array($array))  {
				$this->log->error("Invalid parameters.");
				return null;
			}
			foreach ($array as $name => $value) {
				$name = ucwords($name);
				
				$cmd = 'if (method_exists($obj, "get'.$name.'")) { ';
				$cmd .= 'if (is_object($obj->get'.$name.'())) {';
				$cmd .= '	$this->toObject($value, $obj->get'.$name.'()); }';
				$cmd .= ' else { $obj->set'.$name.'($value); }}'; 
				eval($cmd);
			}
			return $obj;
		}
	}
}